package com.ebelter.btlibrary.btble.ble;

import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.text.TextUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;



/**
 * ZCQ on 2017/6/15.
 */

public class BlueToothAgency {

    private static BlueToothAgency instance;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothA2dp mBluetoothA2dp;
    //private BluetoothManager mBluetoothManager;

    private BlueToothAgency() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//        if (mBluetoothAdapter == null) {
//           // return;//说明获取不到蓝牙设备
//        }
//        mBluetoothAdapter.getProfileProxy(mGlobalContext, new BluetoothProfile.ServiceListener() {
//            @Override
//            public void onServiceConnected(int profile, BluetoothProfile proxy) {
//                mBluetoothA2dp = (BluetoothA2dp) proxy;
//            }
//
//            @Override
//            public void onServiceDisconnected(int profile) {
//
//            }
//        }, BluetoothProfile.A2DP);
        //mBluetoothManager = (BluetoothManager) SettingGlobal.mGlobalContext.getSystemService(Context.BLUETOOTH_SERVICE);
    }

    public static BlueToothAgency getInstance() {
        if (instance == null) {
            synchronized (BlueToothAgency.class) {
                if (instance==null){
                    instance = new BlueToothAgency();
                }
            }
        }
        return instance;
    }


    /**
     * 连接蓝牙
     */
    public boolean connect(String address) {
        if (mBluetoothA2dp == null||mBluetoothAdapter==null) {
            return false;
        }
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        return isConnect(device) || connect(mBluetoothA2dp, device);
    }

    @SuppressWarnings("unchecked")
    private boolean connect(BluetoothA2dp mBluetoothA2dp, BluetoothDevice device) {
        try {
            Class cHeadset = Class.forName("android.bluetooth.BluetoothA2dp");
            Method connMethod = cHeadset.getMethod("connect", BluetoothDevice.class);
            return (boolean) connMethod.invoke(mBluetoothA2dp, device);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 判断一个设备是否正在连接
     */
    public boolean isConnect(BluetoothDevice device) {
        if (device == null || mBluetoothA2dp == null) {
            return false;
        }
        int state = mBluetoothA2dp.getConnectionState(device);
        return state == android.bluetooth.BluetoothHeadset.STATE_CONNECTED;
        // return mBluetoothManager.getConnectionState(device,BluetoothProfile.A2DP)==BluetoothProfile.STATE_CONNECTED;

    }

    /**
     * 判断一个设备是否是绑定的设备
     */
    public boolean isBondDevice(BluetoothDevice device) {
        return device != null && device.getBondState() == BluetoothDevice.BOND_BONDED;
    }


    /**
     * 判断bluetooth是否开启
     */
    public boolean isBluetoothOpen() {
        return mBluetoothAdapter != null && mBluetoothAdapter.getState() == BluetoothAdapter.STATE_ON;
        // return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled();
    }

    /**
     * 得到所有已经配对的蓝牙适配器对象 建议在子线程里面运行
     */
    public List<BluetoothDevice> getBondedDevices() {

        if (mBluetoothAdapter==null){
            return null;
        }
        Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
        if (devices != null && devices.size() > 0) {
            List<BluetoothDevice> datas = new ArrayList<>();
            for (BluetoothDevice device : devices) {
                //得到BluetoothDevice对象,也就是说得到配对的蓝牙适配器
                if (isUse(device)) {
                    datas.add(device);
                }
            }
            datas=removeRepeat(datas);
            return datas;
        }
        return null;
    }


    /**
     * 去除list重复值 建议在子线程里面执行
     */
    private List<BluetoothDevice> removeRepeat(List<BluetoothDevice> mList) {

        for (int i = 0; i < mList.size(); i++) { //外循环是循环的次数

            String ssid = mList.get(i).getAddress();

            for (int j = mList.size() - 1; j > i; j--) {
                String temp_Address = mList.get(j).getAddress();
                if (ssid.equals(temp_Address)) {
                    mList.remove(j);
                }
            }
        }
        return mList;
    }


    public boolean isUse(BluetoothDevice device) {
        return !(device == null || TextUtils.isEmpty(device.getAddress()) || TextUtils.isEmpty(device.getName()));

    }

    /**
     * 打开蓝牙
     */
    public void openBluetooth() {
        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.enable();
        }
    }

    /**
     * 关闭蓝牙
     */
    public void closeBluetooth() {
        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.disable();
        }
    }

//    /**
//     * 获取蓝牙地址
//     */
//    //String macAddress = android.provider.Settings.Secure.getString(context.getContentResolver(), "bluetooth_address");
//    @SuppressLint("HardwareIds")
//    public String getBlueToothAddress() {
////        if (mBluetoothAdapter != null) {
////            return mBluetoothAdapter.getAddress();
////        } else {
////            return "";
////        }
//        return android.provider.Settings.Secure.getString(mGlobalContext.getContentResolver(), "bluetooth_address");
//    }


    /**
     * 判断蓝牙是否正在扫描
     */
    public boolean isDiscovering() {
        return mBluetoothAdapter != null && mBluetoothAdapter.isDiscovering();
    }

    /**
     * 蓝牙关闭扫描
     */
    public boolean cancelDiscovery() {
        return mBluetoothAdapter != null && mBluetoothAdapter.cancelDiscovery();
    }

    /**
     * 蓝牙开始扫描
     */
    public boolean startDiscovery() {
        return mBluetoothAdapter != null && mBluetoothAdapter.startDiscovery();
    }


    /**
     * 断开连接的
     */
    @SuppressWarnings("unchecked")
    public boolean disConnect(BluetoothDevice device) {

        if (device == null || mBluetoothAdapter == null) {
            return false;
        }
        try {
            Class cHeadset = Class.forName("android.bluetooth.BluetoothA2dp");
            Method connMethod = cHeadset.getMethod("disconnect", BluetoothDevice.class);
            return (boolean) connMethod.invoke(mBluetoothA2dp, device);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }


    /**
     * 取消设备的配对
     */
    public boolean unPairDevice(BluetoothDevice device) {
        if (device != null) {
            try {
                Method m = device.getClass()
                        .getMethod("removeBond");
                return (Boolean) m.invoke(device);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }


//    public boolean createBond(Class btClass,BluetoothDevice btDevice) throws Exception {
//        Method createBondMethod = btClass.getMethod("createBond");
//        Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
//        return returnValue.booleanValue();
//    }
//
//    public boolean removeBond(Class btClass,BluetoothDevice btDevice) throws Exception {
//        Method removeBondMethod = btClass.getMethod("removeBond");
//        Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
//        return returnValue.booleanValue();
//    }


}
